package org.goodsence.framework.websocket;

import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @author zty
 * @apiNote
 * @project_name the-revolt
 * @user tain
 * @create_at 2023/6/16 4:32
 * @create_vio IntelliJ IDEA
 */
public class WebSocketUtils {

    private WebSocketUtils() {

    }

    private static final Set<WebSocketSession> sessions = new HashSet<>();

    public static Set<WebSocketSession> getSessions() {
        return sessions;
    }

    /**
     * 发送消息
     * @param message
     * @throws IOException
     */
    public static void sendString(String message) throws IOException {
        for (WebSocketSession session : sessions) {
            if (session.isOpen()) {
                session.sendMessage(new TextMessage(message));

            }
        }
        System.out.println("webSocket发送消息，内容：{}，当前连接数：{}" + message + sessions.size());
    }
    /**
     * 发送消息
     * @param map
     * @throws IOException
     */
    public static void sendMap(Map<String, Object> map) throws IOException {
        System.out.println("webSocket发送消息，内容：{}，当前连接数：{}" + map + sessions.size());
        for (WebSocketSession session : sessions) {
            if (session.isOpen()) {
                session.sendMessage(new TextMessage(map.toString()));
            }
        }
    }

//    /**
//     * 发送消息
//     * @param map
//     * @throws IOException
//     */
//    public static void sendList(List<Object> map , String type) throws IOException {
//        if (sessions.size() > 0) {
//            for (WebSocketSession webSocket : sessions) {
//                if (webSocket.isOpen()) {
//                    String urlType = getWebsocketUrlType(Objects.requireNonNull(webSocket.getUri()).toString());
//                    if (type.equals(urlType)) {
//                        webSocket.sendMessage(new TextMessage(map.toString()));
//                    }
//                }
//            }
//            logger.debug("webSocket发送消息，内容：{}，当前连接数：{}", JsonUtils.toJSONString(map), sessions.size());
//        }
//    }
}
